package com.jhw.ymcc.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.jhw.ymcc.constants.IntegralConstants;
import com.jhw.ymcc.domain.UserIntegral;
import com.jhw.ymcc.domain.UserIntegralLog;
import com.jhw.ymcc.dto.IntegralDto;
import com.jhw.ymcc.exception.GlobalCustomException;
import com.jhw.ymcc.exception.GlobalErrorCode;
import com.jhw.ymcc.mapper.UserIntegralMapper;
import com.jhw.ymcc.service.IUserIntegralLogService;
import com.jhw.ymcc.service.IUserIntegralService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.jhw.ymcc.util.AssertUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jhw
 * @since 2022-10-10
 */
@Service
public class UserIntegralServiceImpl extends ServiceImpl<UserIntegralMapper, UserIntegral> implements IUserIntegralService {


    @Autowired
    private IUserIntegralLogService userIntegralLogService;

    /**
     * 推荐人注册送积分
     * @param userId
     */
    @Override
    public void integralFromRegister(Long userId) {
        // 添加积分表
        saveIntegral(userId,IntegralConstants.REGISTER_INTEGRAL,IntegralConstants.INTEGRAL_STATE_ADD);
        // 添加积分日志表
        saveIntegralLog(userId,IntegralConstants.INTEGRAL_FROM_REGISTER,IntegralConstants.INTEGRAL_STATE_ADD,IntegralConstants.REGISTER_INTEGRAL);
    }

    /**
     * 推荐人购买课程送积分
     * @param dto
     */
    @Override
    public void integralFromReferBuysCourses(IntegralDto dto) {
        Integer integral = getIntegral(dto, IntegralConstants.INTEGRAL_RATIO_FROM_REFER);
        saveIntegral(dto.getId(),integral,IntegralConstants.INTEGRAL_STATE_ADD);
        saveIntegralLog(dto.getId(),IntegralConstants.INTEGRAL_FROM_REFER,IntegralConstants.INTEGRAL_STATE_ADD,integral);
    }

    /**
     * 购买课程送积分
     * @param dto
     */
    @Override
    public void integralFromBuysCourses(IntegralDto dto) {
        Integer integral = getIntegral(dto, IntegralConstants.INTEGRAL_RATIO_FROM_BUY_COURSE);
        saveIntegral(dto.getId(),integral,IntegralConstants.INTEGRAL_STATE_ADD);
        saveIntegralLog(dto.getId(),IntegralConstants.INTEGRAL_FROM_BUY_COURSE,IntegralConstants.INTEGRAL_STATE_ADD,integral);
    }

    /**
     * 充值赠送积分
     * @param dto
     */
    @Override
    public void integralFromRecharge(IntegralDto dto) {
        Integer integral = getIntegral(dto, IntegralConstants.INTEGRAL_RATIO_FROM_RECHARGE);
        saveIntegral(dto.getId(),integral,IntegralConstants.INTEGRAL_STATE_ADD);
        saveIntegralLog(dto.getId(),IntegralConstants.INTEGRAL_FROM_RECHARGE,IntegralConstants.INTEGRAL_STATE_ADD,integral);
    }

    /**
     * 通过userid查询用户积分
     * @param id
     * @return
     */
    @Override
    public UserIntegral getUserIntegral(Long id) {
        return selectOne(new EntityWrapper<UserIntegral>().eq("user_id", id));
    }

    /**
     * 支付抵扣积分
     * @param dto
     */
    @Override
    public void integralDeduction(IntegralDto dto) {
        Integer integral = dto.getIntegral();
        UserIntegral userIntegral = selectOne(new EntityWrapper<UserIntegral>().eq("user_id", dto.getId()));
        AssertUtil.isNotNull(userIntegral, GlobalErrorCode.INTEGRAL_INSUFFICIENT_ERROR);
        if (userIntegral.getIntegral() < integral) {
            throw new GlobalCustomException(GlobalErrorCode.INTEGRAL_INSUFFICIENT_ERROR);
        }
        saveIntegral(dto.getId(),integral,IntegralConstants.INTEGRAL_STATE_REDUCE);
        saveIntegralLog(dto.getId(),IntegralConstants.INTEGRAL_FROM_RECHARGE,IntegralConstants.INTEGRAL_STATE_REDUCE,integral);
    }


    /**
     * 通过金额获取积分
     * @param dto
     * @param integralRatioFromBuyCourse
     * @return
     */
    private Integer getIntegral(IntegralDto dto, Double integralRatioFromBuyCourse) {
        BigDecimal bigDecimal = dto.getMoney().multiply(BigDecimal.valueOf(integralRatioFromBuyCourse));
        return bigDecimal.setScale(IntegralConstants.INTEGRAL_ROUNDING_METHOD, BigDecimal.ROUND_DOWN).intValue();
    }

    /**
     * 保存积分日志表
     * @param userId 用户id
     * @param from 积分来源
     * @param state 积分状态
     */
    private void saveIntegralLog(Long userId,String from, Integer state,Integer integral) {
        UserIntegralLog userIntegralLog = new UserIntegralLog();
        userIntegralLog.setIntegral(integral);
        userIntegralLog.setCreatime(new Date());
        userIntegralLog.setUserId(userId);
        userIntegralLog.setFromReason(from);
        userIntegralLog.setIntegralState(state);
        userIntegralLogService.insert(userIntegralLog);
    }

    /**
     * 保存积分表
     * @param userId
     * @param integral
     */
    private void saveIntegral(Long userId, Integer integral,Integer state) {
        UserIntegral userIntegral = selectOne(new EntityWrapper<UserIntegral>().eq("user_id", userId));
        if (userIntegral != null) {
            if (IntegralConstants.INTEGRAL_STATE_REDUCE.equals(state)) {
                userIntegral.setIntegral(userIntegral.getIntegral() - integral);
            } else {
                userIntegral.setIntegral(userIntegral.getIntegral() + integral);
            }
            super.updateById(userIntegral);
            return;
        }
        UserIntegral saveIntegral = new UserIntegral();
        saveIntegral.setUserId(userId);
        saveIntegral.setIntegral(integral);
        insert(saveIntegral);
    }
}
